package com.fzrskj.cloud.free.sys.utils;

import com.alibaba.fastjson.JSONObject;
import com.fzrskj.cloud.free.core.tool.CMailTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.sys.bean.Mail;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import ms.core.db.ConnectionContext;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;

/**
 * SendMailThread.
 *
 * @author zj.
 *         Created on 2018/8/31 0031.
 */
public class SendMailThread implements Runnable{
    private Mail mail;

    public void setMail(Mail mail) {
        this.mail = mail;
    }

    private Map<String, Object> threadParam;

    public void setThreadParam(Map<String, Object> cdt) {
        this.threadParam = cdt;
    }

    @Override
    public void run() {
        Exception error = null;
        boolean sendOK = false;
        try {
            Boolean flag = CMailTool.sendMail(mail);
            if (!flag) {
                UserLogUtils.addLog(this, 1000, "sendMail", "发送失败，接收者邮箱【" + threadParam.get("receiver") + "】；发送参数【" + JSONObject.toJSONString(mail));
                sendOK = false;
            } else {
                sendOK = true;
            }

            SendMailUtils smu = new SendMailUtils();
            smu.addSysNotifyRecord(threadParam.get("tempName").toString(), threadParam.get("subject").toString(), threadParam.get("message").toString(), mail.getSender(), threadParam.get("receiver").toString(), sendOK);
        } catch (Exception e) {
            error = e;
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            SysRunTimeLogUtils.addLog(this, null == CloudContextUtils.getSession() ?
                    CloudContextUtils.getAdminId() : CloudContextUtils.getSession().getUID(), "SendMailThread", "发送邮件线程异常=【" + sw.toString() + "】");
        } finally {
            if (!sendOK) {
                UserLogUtils.addLog(this, null == CloudContextUtils.getSession() ?
                                CloudContextUtils.getAdminId() : CloudContextUtils.getSession().getUID(),
                        "发送报文=【" + JSONObject.toJSONString(mail) + "】,，异常信息【" + error + "】");
            }

            ConnectionContext.closeAllConnection();
        }

    }
}